package com.newway.wechat.controller;

import com.newway.common.Result;
import com.newway.wechat.entity.OrgEntity;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Arrays;
import java.util.UUID;

/**
 * 文件上传参考
 */
@RequestMapping("/wechat")
@RestController
public class UploadFileController {

    private static final String UPLOAD_DIR = "D:\\images";

    //private static final String UPLOAD_DIR = "uploads/";

    @PostMapping("/upload")
    public Result uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request, @ModelAttribute  OrgEntity orgEntity) {
        try {
            // 1. 验证文件
            if (file.isEmpty()) {
                return Result.fail("请选择文件");
            }
            // 2. 限制文件大小 (10MB)
            long maxSize = 2 * 1024 * 1024;
            if (file.getSize() > maxSize) {
                return Result.fail("文件大小不能超过2MB");
            }
            // 3. 验证文件类型
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            if (!Arrays.asList(".jpg", ".jpeg", ".png", ".gif", ".pdf").contains(fileExtension.toLowerCase())) {
                return Result.fail("不支持的文件类型");
            }
            // 4. 创建存储目录
            File uploadPath = new File(UPLOAD_DIR);
            if (!uploadPath.exists()) {
                uploadPath.mkdirs();
            }
            // 5. 生成唯一文件名
            String fileName = UUID.randomUUID() + fileExtension;
            // 6. 保存文件
            File dest = new File(uploadPath.getAbsolutePath() + File.separator + fileName);
            file.transferTo(dest);

            // 7. 返回访问URL
            String fileUrl = request.getScheme() + "://" + request.getServerName() + ":" +
                    request.getServerPort() + "/" + UPLOAD_DIR + fileName;

            return Result.success();

        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("上传失败: " + e.getMessage());
        }
    }
}
